using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

namespace NiSis.Class
{
    public class ExportUtil
    {
        public static void ConvertGridToCSV(GridView grid, string fileName)
        {
            // Clear the response output stream before start
            HttpContext.Current.Response.Clear();

            // Set the response headers to fit our CSV file
           HttpContext.Current.Response.ContentType = "text/plain";
            HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));

            using (StreamWriter writer = new StreamWriter(HttpContext.Current.Response.OutputStream))
            {
                // Add header row
                writer.WriteLine(GetCSVLine(grid.HeaderRow.Cells));

                // Add all the data rows
                foreach (GridViewRow row in grid.Rows)
                {
                    writer.WriteLine(GetCSVLine(row.Cells));
                }
            }

            // End the current response. Otherwise, excel will open with the whole page inside.
            HttpContext.Current.Response.End();
        }
        private static string GetCSVLine(TableCellCollection cellsToAdd)
        {
            StringBuilder lineBuilder = new StringBuilder();

            bool isFirst = true;
            foreach (TableCell cell in cellsToAdd)
            {
                if (!isFirst)
                {
                    lineBuilder.Append(",");
                }
                isFirst = false;

                lineBuilder.AppendFormat("{1}{0}{1}",cell.Text,(char) 34);
            }
            return lineBuilder.ToString().Replace("&nbsp;", " ").Replace("&amp",string.Empty);
        } 
    }
}
